import xml.dom.minidom
import random
import time

def randstr(digits):
    ret="";
    for i in range(1,digits):
        ret=ret+str(random.randint(0,9));
    return ret;
        
def create_a_document():
    doc = xml.dom.minidom.Document();
    document_element = doc.createElement("document");
    doc.appendChild(document_element);
    return doc, document_element;

def add_a_list(doc,doc_el,elementname):
    element=doc.createElement(elementname);
    doc_el.appendChild(element);
    return element;

def add_a_torun_element(doc,torunlist,num=None):
    if num==None:
        num=randstr(3);
    else:
        num=str(num);
    job = doc.createElement("FDTDjob");
    job.setAttribute("file","Z:/Simulations/2010-11-02/bowtie_meshsize_25e-"+num+".fsp");
    torunlist.appendChild(job);
    return job;

def add_a_completed_element(doc,completedlist,outcome,num=None):
    job = doc.createElement("FDTDjob");
    if num==None:
        num=randstr(3);
    else:
        num=str(num);
    job.setAttribute("file","Z:/Simulations/2010-11-02/bowtie_meshsize_25e-"+num+".fsp");
    #job.setAttribute("completed","true");
    job.setAttribute("success",str(outcome));
    job.setAttribute("starttime",str(time.time()));
    job.setAttribute("endtime",str(time.time()+random.randint(0,3600)));
    completedlist.appendChild(job);
    return job;


def write_to_screen(doc):
    print doc.toprettyxml();

def write_to_file(doc, name="fdtd-jobs-list.xml"):
    fileobj = open(name,"w");
    fileobj.write(doc.toprettyxml());
    fileobj.close();

def refresh_list_file(numreps=3, numtorun=10, numsucceeded=0, numfailed=0):
    doc, doc_el = create_a_document()
    for reps in range(numreps):
        if numtorun>0:
            rl = add_a_list(doc,doc_el,"torun");
            for i in range(numtorun):
                add_a_torun_element(doc,rl,reps*numtorun+i+1);
        if numsucceeded>0 or numfailed>0:
            cl = add_a_list(doc,doc_el,"completed");
            if numsucceeded>0:
                for i in range(numsucceeded):
                    add_a_completed_element(doc,cl,True,numreps*numsucceeded-(reps*numsucceeded+i));
            if numfailed>0:
                for i in range(numfailed):
                    add_a_completed_element(doc,cl,False,numreps*numfailed-(reps*numfailed+i));
    write_to_file(doc);
